package com.easy.project.config.serialize;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.TimeZone;

/**
 * web请求响应序列化配置
 *
 * @author wxz
 */
@Configuration
public class WebSerializeConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        WebMvcConfigurer.super.configureMessageConverters(converters);
        // 增加自定义的序列化类型 必须放在第一个进行处理  不然会被其他的处理器处理
        converters.add(0,new MappingJackson2HttpMessageConverter(objectMapper()));
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        WebMvcConfigurer.super.addFormatters(registry);
        // 前端字符串日期转localdate 不需要
        // registry.addFormatter(new JacksonSerializeConfig.LocalDateFormatter());
        // 前端字符串日期转localdateTime
        // registry.addFormatter(new JacksonSerializeConfig.LocalDateTimeFormatter());
    }

    public ObjectMapper objectMapper() {
        return Jackson2ObjectMapperBuilder.json()
                .timeZone(TimeZone.getDefault())
                // 防止long返回给前端精度丢失
                .serializerByType(Long.class, new ToStringSerializer())
                .serializerByType(LocalDate.class, new JacksonSerializeConfig.ToLocalDateSerializer())
                .serializerByType(LocalDateTime.class, new JacksonSerializeConfig.ToLocalDateTimeSerializer())
                // 防止decimal返回给前端精度丢失
                .serializerByType(BigDecimal.class, new ToStringSerializer())
                // 设置boolean 类型
                .serializerByType(Boolean.class,new JacksonSerializeConfig.ToBooleanSerializer())
                .build();
    }
}
